// pages/addSchedule/index.js
import { changeParticipantInfo, delParticipantInfo } from '../../api/information'
import { getQualificateList } from '../../api/qualificate'
import REG from "../../utils/reg";
import { removeObj } from '../../utils/removeObj.js'
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    navIndex:0,
    participantId:'',
    qualificateIds:'',
    applyId:'',
    buttoncolor: false,
    userId:'',
    hasSkuQualificate:'',
    userFormList: [
      { name: '姓名 Name', type: 'text', request: 1, mode: '', check: 'text', value: '', placeholder: '请填写真实姓名', errTitle: '' },
      { name: '性别 Gender', type: 'button', request: 1, mode: '', value: 0, select: ['男 Man', '女 Lady'], placeholder: '请填写真实姓名', errTitle: '' },
      { name: '手机号码 Cellphone', type: 'Number', request: 1, mode: '', check: 'phone', value: '', placeholder: '请填写手机号码', errTitle: '' },
      { name: '证件类型 Type of certificate', type: 'picker', request: 1, mode: 'select', select: ['请选择证件类型', '身份证', '护照', '港澳居民来往内陆通行证', '台胞证'], value: 0, placeholder: '请选择证件类型', errTitle: '' },
      { name: '证件号码 ID', type: 'Number', request: 1, mode: '', check: 'card', value: '', placeholder: '请根据证件类型填写正确证件号码', errTitle: '' },

      { name: '出生日期 Birthdate', type: 'picker', request: 1, mode: 'date', value: '', placeholder: '请选择出生日期', errTitle: '' },
      { name: '血型 Blood type', type: 'picker', request: 1, mode: 'select', select: ['请选择血型', 'A', 'B', 'AB', 'O', 'Rh', '不详'], value: 0, placeholder: '请选择血型', errTitle: '' },
      { name: '服装尺码 T-shirt size', type: 'picker', request: 1, mode: 'select', select: ['请填写服装尺码', 'XS', 'S', 'M', 'L', 'XL', 'XXL', 'XXXL'], placeholder: '请填写服装尺码', value: 0, errTitle: '' },
      { name: '紧急联系人 Emergency contact', type: 'text', request: 1, mode: '', value: '', placeholder: '请填写紧急联系人姓名', errTitle: '' },
      { name: '紧急联系人手机号码 Emergency contact phone', type: 'Number', request: 1, mode: '', check: 'phone', value: '', placeholder: '请填写紧急联系人手机号码', errTitle: '' },
      { name: '所在地区 Region', type: 'picker', mode: 'multiSelector', request: 1, check: 'picker', value: '', placeholder: '请选择所在地区', errTitle: '' },
      { name: '详细地址 Address', type: 'text', request: 1, mode: '', check: 'text', value: '', placeholder: '请填写所在地区详细地址', errTitle: '' },
      { name: '邮箱 E-mail', type: 'text', request: 1, mode: '', check: 'email', value: '', placeholder: '请填写电子邮箱', errTitle: '' }
    ],
    time: {
      start: 365 * 90 + 25, // 开始时间是今天的前90年
      end: 0 // 结束时间是今天的0天后
    },
    start: '1930-4-15',
    end: '2020-4-17',
    isRequst: false,//用来判断当前是否为请求状态
    multiIndex: [0, 0, 0],
    multiArray: [],
    multiIndex: [0, 0, 0],
    multiArray: [],
    qualificateList:[]
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.text){
      wx.setNavigationBarTitle({title: options.text})
    }
    let d = JSON.parse(options.user)
    var pages = getCurrentPages(); //页面指针数组
    var prepage = pages[pages.length - 2]; //上一页面指针
    if (prepage.route == "pages/participant_news/index") { //参赛信息列表页进入
    } else {
      d.shortAddress = d.shortAddress1
    }
    let arr = this.data.userFormList;
    arr[0].value = d.name; //姓名
    arr[1].value = d.sex == 1 ? 0 : 1;//性别
    arr[2].value = d.phone // 手机号码
    arr[3].value = d.certificateType?arr[3].select.indexOf(d.certificateType):0 // 证件类型
    arr[3].value = arr[3].value < 0 ? 0 : arr[3].value
    arr[4].value = d.identity // 证件号码
    arr[5].value = d.birthday.split(' ')[0] // 出生日期
    arr[6].value = d.bloodType ? arr[6].select.indexOf(d.bloodType) : 0 // 血型
    arr[6].value = arr[6].value < 0 ? 0 : arr[6].value
    arr[7].value = d.size ? arr[7].select.indexOf(d.size) : 0 // 服装尺寸
    arr[7].value = arr[7].value < 0 ? 0 : arr[7].value
    arr[8].value = d.linkMan//紧急联系人
    arr[9].value = d.linkPhone // 紧急联系人电话
    // arr[10].value = d.name // 所在地区（在后面设置）
    arr[11].value = d.address
    arr[12].value = d.email
    // console.log(arr)
    this.setData({ userFormList: arr, participantId: d.participantId, name: d.name})
    app.getIndex(d.shortAddress.split(','), e => {
      this.setData({ ...app._processingAreaData(e) })
    })
    let { start, end } = this.data.time
    let day1 = new Date().valueOf();
    // let startTime = new Date(day1 - (24 * 60 * 60 * 1000 * start));
    let endTime = new Date(day1 + (24 * 60 * 60 * 1000 * end));
    // let start1 = startTime.getFullYear() + '-' + (startTime.getMonth() + 1) + '-' + startTime.getDate();
    let end1 = endTime.getFullYear() + '-' + (endTime.getMonth() + 1) + '-' + endTime.getDate();
    // this.setData({ start: start1, end: end1 })
    this.setData({ end: end1 })
  },
  onShow(){
    this._getQualificateList()
  },
  getNavIndex(e){
    this.setData({ navIndex:e.currentTarget.dataset.index})
    this._getQualificateList()
  },
  _getQualificateList(){
    let { navIndex, participantId } = this.data
    if (navIndex) {
      getQualificateList(participantId).then(res => {
        this.setData({ qualificateList: removeObj(res.data, ['searchValue', 'createBy', 'createTime', 'updateBy', 'updateTime', 'params', 'remark', 'orderId', 'userName', 'checkTime']) })
      })
    }
  },

  // 输入框赋值
  getInputValue(e) {
    this.setData({ [`userFormList[${e.currentTarget.dataset.index}].value`]: e.detail.value })
    let { check, value } = this.data.userFormList[e.currentTarget.dataset.index]
    let errTitle = ''
    switch (check) {
      case 'phone':
        errTitle = REG.isPoneAvailable(value) ? '' : '请填写正确的手机号码'
        break;
      case 'email':
        errTitle = REG.isEmail(value) ? '' : '请填写正确的邮箱'
        break;
      case 'card':
        if (this.data.userFormList[3].value == 1) {
          errTitle = REG.isIdCard(value) ? '' : '请填写正确的身份证号码'
        }
        break;
      default:
        break;
    }
    this.setData({ [`userFormList[${e.currentTarget.dataset.index}].errTitle`]: (errTitle != '' ? errTitle : '') })
  },
  // 性别切换
  bindBtn(e) {
    this.setData({ [`userFormList[${e.currentTarget.dataset.parindex}].value`]: e.currentTarget.dataset.index })
  },
  //Picker选择（非地区选择）
  bindPickerChange: function (e) {
    this.setData({ [`userFormList[${e.currentTarget.dataset.index}].value`]: e.detail.value })
    let { type, mode, placeholder, value } = this.data.userFormList[e.currentTarget.dataset.index]
    console.log(e)
    if (type == 'picker' && (mode == 'select' || mode == 'date')) {
      this.setData({ [`userFormList[${e.currentTarget.dataset.index}].errTitle`]: (value == 0 ? placeholder : '') })
    }
  },
  //Picker地区选择
  bindMultiPickerColumnChange(e) {
    let multiIndex = this.data.multiIndex
    multiIndex[e.detail.column] = e.detail.value
    this.setData({ ...app._processingAreaData(multiIndex) })
  },
  //检查填写项
  checkValue(callback) {
    let { userFormList } = this.data
    let state = true
    userFormList.forEach((e, i) => {
      if (e.request == 1 && e.mode != 'multiSelector') { // 没有报错项必填项和非地区picker
        if (e.type == 'text' || e.type == 'Number') {
          if (e.value == '') {
            e.errTitle = e.placeholder
          } else {
            switch (e.check) {
              case 'phone':
                e.errTitle = REG.isPoneAvailable(e.value) ? '' : '请填写正确的手机号码'
                break;
              case 'card':
                if (userFormList[3].value == 1) {
                  e.errTitle = REG.isIdCard(e.value) ? '' : '请填写正确的身份证号码'
                }
                break;
              case 'email':
                e.errTitle = REG.isEmail(e.value) ? '' : '请填写正确的邮箱'
                break;
            }
          }
        } else if (e.type == 'picker') {
          if (e.mode == 'select') { // 单选择器
            if (e.value<=0) {
              e.errTitle = e.placeholder
            }
          } else if (e.mode == 'date') { // 日期选择器
            if (e.value == '') {
              e.errTitle = e.placeholder
            }
          }
        }
        if (e.errTitle != '' && state) {
          state = false
        }
      }
      if (i == userFormList.length - 1) {
        this.setData({ userFormList: userFormList })
        if (!state) {
          wx.showToast({ title: '请检查填写项', icon: 'none' })
        }
        callback(state)
      }
    })
  },
  // 确认信息
  submit() {
    if (!this.data.isRequst){
      //校验报名人
      let { userFormList, multiArray, multiIndex, participantId } = this.data
      this.checkValue(state => {
        if (state) {
          this.setData({ isRequst: true })
      let address = '';
      if (multiArray[0][multiIndex[0]]) {
        address += multiArray[0][multiIndex[0]]
      }
      if (multiArray[1][multiIndex[1]]) {
        address += (',' + multiArray[1][multiIndex[1]])
      }
      if (multiArray[2][multiIndex[2]]) {
        address += (',' + multiArray[2][multiIndex[2]])
      }
      let obj = {
        participantId:participantId,
        name: userFormList[0].value,
        sex: Number(userFormList[1].value) + 1,
        phone: userFormList[2].value,
        certificateType: userFormList[3].select[userFormList[3].value],
        identity: userFormList[4].value,
        birthday: userFormList[5].value,
        bloodType: userFormList[6].select[userFormList[6].value],
        size: userFormList[7].select[userFormList[7].value],
        linkMan: userFormList[8].value,
        linkPhone: userFormList[9].value,
        shortAddress: address,
        address: userFormList[11].value,
        email: userFormList[12].value
      }
      changeParticipantInfo(obj).then(res => {
        if (res.code == 0) {
          this.showToast('修改成功')
          this.navigateBack(2000)
          this.setData({ isRequst: false })
        } else {
          this.showToast('修改失败','none')
          this.setData({ isRequst: false })
        }
      })
        }
      })
    }
  },
  _delParticipantInfo() {
    wx.showModal({
      title: '',
      content: '删除信息后无法恢复确定删除？',
      success:res=> {
        if (res.confirm) {
          if (!this.data.isRequst) {
            this.setData({ isRequst: true })
          delParticipantInfo({ ids: [this.data.participantId]}).then(res => {
            if (res.code == 0) {
              this.showToast('已删除','success')
              this.navigateBack(0)
            } else {
              this.showToast('删除失败')
              this.setData({ isRequst: false })
            }
          })
          }
        }
      }
    })
  },
  goto(e){
    let u = e.currentTarget.dataset.item;
    let { name, userId, hasSkuQualificate, participantId, qualificateIds} = this.data
    wx.navigateTo({
      url: `/pages/qualification_supplement/index?title=${u.qualificateName}&userName=${name}&uid=${userId}&hasSkuQualificate=${u.status}&pid=${u.participantId}&qualificateIds=${u.qualificateId}&applyId=${u.applyId}&arr=${JSON.stringify(u.imageList)}&type=send`,
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    let { navIndex } = this.data
    if (navIndex==1) {
      this._getQualificateList()
    }else{
      wx.stopPullDownRefresh()
    }
  },
  add(){
    let { userId, participantId } = this.data
    wx.navigateTo({
      url: `/pages/input_information/index?add=true&stop=true&pid=${participantId}&uid=${userId}`
    })
  },
  showToast(title, icon = 'none', duration=2000){
    wx.showToast({
      title: title,
      icon: icon,
      duration: duration
    })
  },
  navigateBack(time = 3000) {
    setTimeout(function() {
      wx.navigateBack(1)
    }, time);
  }
})